package com.gzsj.genealogyManagement.people.controller;


import com.gzsj.common.core.controller.BaseController;
import com.gzsj.common.core.domin.AjaxResult;
import com.gzsj.genealogyManagement.people.domin.People;
import com.gzsj.genealogyManagement.people.service.PeopleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;


@Controller
@RequestMapping("/")
public class PeopleController extends BaseController {



    @Autowired
    private PeopleService peopleService;


    @GetMapping("exportDocx")
    public ResponseEntity<?> exportDocx() {

        try {

            peopleService.exportDocx();
            return ResponseEntity.ok(AjaxResult.success("文件已生成成功"));
        }catch (Exception e){

            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(AjaxResult.error("文件已生成失败: " + e.getMessage()));
        }
    }


    /**
     * 生成pdf下载链接、完成pdf文档的下载
     * @param filePath
     * @return
     * @throws Exception
     */
    @GetMapping("download/document")
    public ResponseEntity<Resource> downloadFile(@RequestParam String filePath) throws Exception {
        Path path = Paths.get(filePath);
        Resource resource = new UrlResource(path.toUri());
        if (resource.exists() && resource.isReadable()) {
            // 确定文件的内容类型
            String contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; // DOCX MIME类型
            String pathName = path.getFileName().toString();

            // 对文件名进行URL编码
            String encodedFileName = URLEncoder.encode(pathName, StandardCharsets.UTF_8.toString());

            // 设置HTTP头部信息
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + pathName + "\"; filename*=UTF-8''" + encodedFileName);
            headers.add(HttpHeaders.CONTENT_TYPE, contentType);

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } else {
            throw new RuntimeException("Could not read the file!");
        }
    }



}





